package com.pomr.service.common.impl;

import java.util.Date;
import java.util.List;

import com.pomr.model.simstorage.SimFlow;
import com.pomr.model.simstorage.SimStorageDetail;
import com.pomr.model.sys.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.base.BaseDao;
import com.pomr.model.form.AgencyUp;
import com.pomr.model.form.PersonRecordUp;
import com.pomr.model.health.PersonRecord;
import com.pomr.model.sys.Agency;
import com.pomr.model.sys.User;
import com.pomr.service.common.CommonService;
@Service
public class CommonServiceImpl implements CommonService {
	@Autowired
	@Qualifier("baseDaoImpl")
	private BaseDao basedao;
	@Override
	public List findSimByIdCard(String cont) throws Exception {
		String hql = "from Receive  r where (r.receiveTime =null or r.receiveTime='') "
				+ "and (r.record.name like '"+cont+"%' or r.record.idcard like '"+cont+"%')";
		return basedao.findByHqlNoCache(hql);
	}
	@Override
	public List findRolesByUser(User user) throws Exception {
		String hql = "from Role r where r.id = (select u.role.id from User u where u.id="+user.getId()+")";
		List<Role> roles = basedao.findByHql(hql);
		if(roles!=null && !roles.isEmpty()){
			Role role = roles.get(0);
			if(role.getType()!=null && role.getType()==1){//超级管理员 可以分配超管权限
				hql = "from Role where status!=-1 or status=null";
				return basedao.findByHql(hql);
			}
		}
		hql = "from Role where (type!=1 or type=null) and  (status!=-1 or status=null)";
		return basedao.findByHql(hql);
	}
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean loadPersonRecords(List<PersonRecordUp> prus) throws Exception {
		if(prus==null || prus.size()<=0){
			return false;
		}
		for(PersonRecordUp pru:prus){
			PersonRecord pr = pru.getRecord();
			//获取所属机构
			String hql = "from Agency where identifier = '"+pru.getAgency()+"'";
			Agency ag = (Agency) basedao.findByHql(hql).get(0);
			if(ag == null){
				throw new Exception("所属机构不存在");
			}
			pr.setAgency(ag);
			
			//判断身份证号是否已经存在
			hql = "from PersonRecord where idcard = '"+pru.getIdcard()+"'";
			List<PersonRecord> prs = basedao.findByHql(hql);
			if(prs==null || prs.size()<=0){
				pr.setCreateTime(new Date());
				if(!basedao.add(pr)){
					throw new Exception("保存档案失败，身份证号："+pru.getIdcard());
				}
			}else{
				throw new Exception("身份证号"+pru.getIdcard()+"的档案已经存在");
			}
		}
		return true;
	}
	
	
	public Agency findAgency(int key) throws Exception {
		String hql = "from Agency where id = "+key;
		List<Agency> ags1 = basedao.findByHqlNoCache(hql);
		return ags1.get(0);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public int loadAgency(AgencyUp agu) throws Exception{
		//判断上级机构编号是否准确
		if(agu.getParentAgency()==null || agu.getParentAgency().equals("")){
			agu.setParentAgency("3702");
		}
		String hql = "from Agency where identifier = '"+agu.getParentAgency()+"'";
		List<Agency> ags = basedao.findByHql(hql);
		if(ags==null || ags.size()<=0){
			throw new Exception(agu.getParentAgency()+"机构不存在");
		}
		Agency ag = agu.getLoadAgency();
		ag.setPidentifier(agu.getParentAgency());
		ag.setPatientName(ags.get(0).getName());
		ag.setPatientId(ags.get(0).getId());
		ag.setCreateTime(new Date());
		User u = new User();
		hql = "from User where id = 1";
		u = (User) basedao.findByHql(hql).get(0);
		ag.setCreateUser(u);
		ag.setCreateName(u.getName());
		int key = 0;
		if(!((key = basedao.addNumKey(ag))>0)){
			throw new Exception("上传机构信息失败");
		}
		return key;
	}

	@Override
	public List<SimStorageDetail> findAllSims() throws Exception {
		String hql = "from SimStorageDetail where equipmentCon.id!=3 ";
		return basedao.findByHql(hql);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveFlows(List<SimFlow> flows) throws Exception {
		//查询对应的detail信息
		String hql = "from SimStorageDetail where iccid='";
		for(SimFlow flow:flows){
			List<SimStorageDetail> details = basedao.findByHql(hql+flow.getIccid()+"'");
			flow.setDetail(details.get(0));
		}
		if(!basedao.batchSaveOrUpdate(flows)){
			throw new Exception("保存失败");
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean clearFlows() throws Exception {
		String hql = "delete from SimFlow";
		return basedao.editNumHql(hql)>=0;
	}
}
